use mysql::prelude::*;

use crate::MySQLUserPrelude;

pub async fn query_grants(
    pool: &mysql::Pool,
    user: &str,
    from_mysql_user_prelude: &MySQLUserPrelude,
) -> MySQLUserPrelude {
    let mut mysql_user_prelude = MySQLUserPrelude::default();
    let mut query_privs = vec![];
    let mut sys_privs = vec![];
    for (sys_priv, table_priv) in from_mysql_user_prelude.permissible_static_privileges.clone() {
        for user_sys_priv in from_mysql_user_prelude.sys_privs.clone() {
            if user_sys_priv.eq_ignore_ascii_case(&sys_priv) {
                query_privs.push(table_priv.clone());
                sys_privs.push(sys_priv.to_lowercase());
                break;
            }
        }
    }

    let sql = format!("SELECT {} FROM mysql.user WHERE user = '{user}'", query_privs.join(","));
    let mut result =sql.run(pool).unwrap();

    while let Some(result_set) = result.iter() {
        for row in result_set {
            let row = row.unwrap();
            for idx in 0..query_privs.len(){
                let data = row.get::<String, usize>(idx);
                if data == Some(String::from("Y")) {
                    // 有权限
                    let sys_priv = sys_privs.get(idx).unwrap();
                    mysql_user_prelude.sys_privs.push(sys_priv.to_string());
                }
            }
        }
    }

    mysql_user_prelude
}
